from flask import Blueprint, jsonify, session, render_template, request, redirect

from config import db
from models.models import ShopCar

shopping = Blueprint('shopping', __name__)


@shopping.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


# 获取所有用户信息
@shopping.route("/shopping/car")
def get_car_info_by_userid():
    user_id = session.get("user_id")
    types = ShopCar.query.filter_by(user_id=user_id)
    data = []
    for _type in types:
        value = {
            'good_id': _type.good_id,
            'name': _type.name,
            'price': _type.price,
            'number': _type.number,
            'type': _type.type,
            'outline': _type.outline,
            'img_url': _type.img_url,
            'link_url': _type.link_url,

        }
        data.append(value)
    return jsonify({'code': 0, 'count': len(data), "msg": "", 'data': data})


@shopping.route("/user/car")
def user_car():
    return render_template('shopping_cart.html')


@shopping.route('/add/car/good', methods=['POST'])
def add_order_good():
    user_id = session.get("user_id")
    if request.method == 'POST':
        # 从请求中获取表单数据
        good_id = request.form.get('good_id')
        name = request.form.get('name')
        price = request.form.get('price')
        number = request.form.get('number')
        _type = request.form.get('type')
        outline = request.form.get('outline')
        img_url = request.form.get('img_url')
        link_url = request.form.get('link_url')

        shop_car_item = ShopCar(
            user_id=user_id,
            good_id=good_id,
            name=name,
            price=price,
            number=number,
            type=_type,
            outline=outline,
            img_url=img_url,
            link_url=link_url
        )

        db.session.add(shop_car_item)
        db.session.commit()
        url = '/get/good/detail/' + str(good_id)
        return redirect(url)
    return "请求失败"
